<template>
	<view class="container">
		<view class="form-group">
			<text>姓名：</text>
			<input type="text" placeholder="请输入姓名" @input="bindNameInput" />
		</view>
		<view class="form-group">
			<text>身份证号码：</text>
			<input type="text" placeholder="请输入身份证号码" @input="bindIdCardInput" />
		</view>
		<button @tap="submit">提交</button>
		<view class="message">{{ message }}</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		shiming
	} from '@/package/api/shimingapi.js';

	const name = ref('');
	const idCard = ref('');
	const message = ref('');
	const countdown = ref(2);

	const bindNameInput = (e) => {
		name.value = e.detail.value;
	};

	const bindIdCardInput = (e) => {
		idCard.value = e.detail.value;
	};

	const submit = () => {
		if (!name.value || !idCard.value) {
			message.value = '姓名和身份证号码不能为空';
			return;
		}
		console.log("请求");

		shiming({
				name: name.value,
				idCard: idCard.value
			})
			.then((res) => {
				console.log(res)
				if (res.code == 200) {

					message.value = '实名认证成功';
					uni.setStorageSync('isrealnameauthenticated', 1);
					uni.showToast({
						title: `实名认证成功，将在 ${countdown.value} 秒后返回上一级页面`,
						icon: 'none',
						duration: 1000
					});
					const timer = setInterval(() => {
						countdown.value--;
						if (countdown.value > 0) {
							uni.setStorageSync('isrealnameauthenticated', 1);
							uni.showToast({
								title: `将在 ${countdown.value} 秒后返回上一级页面`,
								icon: 'none',
								duration: 1000
							});
						} else {
							clearInterval(timer);
							uni.navigateBack({
								delta: 1,
								success: () => {
									uni.setStorageSync('isrealnameauthenticated', 1);
									console.log('返回上一级页面成功');
								},
								fail: (err) => {
									console.error('返回上一级页面失败', err);
								}
							});
						}
					}, 1000);
				} else if (res.code == -1) {
					message.value = '实名认证失败：' + res.message;
				}
			})
			.catch((error) => {
				console.error("请求失败:", error);
				message.value = '请求失败，请稍后再试';
			});
	};
</script>

<style scoped>
	.container {
		padding: 20px;
		background-color: #fff;
	}

	.form-group {
		margin-bottom: 15px;
	}

	input {
		border: 1px solid #ccc;
		padding: 5px;
		width: 100%;
	}

	button {
		background-color: #007aff;
		color: white;
		padding: 10px;
		width: 100%;
	}

	.message {
		margin-top: 10px;
		color: red;
	}
</style>